<template>
  <div id="BdMapId"></div>
</template>

<script>
export default {
  data() {
    return {
      map: null,
      localSearch: null,
      pointList: [],
    };
  },
  mounted() {
    this.getBmap();
  },
  methods: {
    //地图初始化
    getBmap() {
      //设置地图最大最小级别
      this.map = new BMapGL.Map("BdMapId", {
        minZoom: 5,
        maxZoom: 21,
      }); // 创建Map实例

      var point = new BMapGL.Point(112.532959, 37.79722); // 创建点坐标
      this.map.centerAndZoom(point, 11); // 初始化地图，设置中心点坐标和地图级别
      this.map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      var localSearch = new BMapGL.LocalSearch(this.map, {
        renderOptions: { map: this.map, autoViewport: true, panel: "r-result" },
        onSearchComplete: (res) => {
          console.log("地图周边res", res);
          if (this.pointList.length > 0) {
            res._pois.forEach((item) => {
              let index = this.pointList.findIndex(
                (pos) => item.uid == pos.uid
              );
              if (index != -1) {
                this.pointList.push({ title: item.title, ...item.point });
              }
            });
          } else {
            res._pois.forEach((item) => {
              this.pointList.push({ title: item.title, ...item.point });
             
            });
          }
        },
        pageCapacity: 100,
      });

      this.map.addEventListener("dragend", (e) => {
        // 获取拖拽后地图的中心点
        var center = this.map.getCenter();
        console.log("地图中心点坐标：", center.lng, center.lat);
        console.log(e);
        localSearch.searchInBounds("收费站", this.map.getBounds());
        if (this.pointList.length > 20) {
          // this.exportData()
        }
        console.log(this.pointList, "存储数据");
      });
    
    },
    exportData() {
      // 将数据转换为JSON字符串
      const jsonData = JSON.stringify(this.pointList);
      // 创建一个Blob对象，并使用它创建一个链接元素
      const blob = new Blob([jsonData], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      // 创建一个a标签用于触发下载
      const downloadLink = document.createElement("a");
      downloadLink.href = url;
      downloadLink.download = "data.json"; // 下载文件的名称
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    },
  },
};
</script>

<style>
#BdMapId {
  height: 100%;
}
</style>